/**
 * 邀约活动管理页面JavaScript
 * 基于Apple Design System的交互设计
 * 版本：v1.0
 * 创建时间：2025-07-20
 */

// 全局变量
let currentView = 'table';
let currentActivityId = null;
let activities = [];
let filteredActivities = [];

// DOM 元素
const searchInput = document.getElementById('search-input');
const searchClear = document.getElementById('search-clear');
const statusFilter = document.getElementById('status-filter');
const typeFilter = document.getElementById('type-filter');
const dateFilter = document.getElementById('date-filter');
const resetFiltersBtn = document.getElementById('reset-filters');
const createActivityBtn = document.getElementById('create-activity-btn');
const activityTemplateBtn = document.getElementById('activity-template-btn');
const exportBtn = document.getElementById('export-btn');
const viewBtns = document.querySelectorAll('.view-btn');
const tableView = document.getElementById('table-view');
const gridView = document.getElementById('grid-view');
const createModal = document.getElementById('create-activity-modal');
const actionMenuModal = document.getElementById('action-menu-modal');

// 页面初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeEventListeners();
    loadActivities();
    updateStats();
});

// 初始化事件监听器
function initializeEventListeners() {
    // 搜索功能
    searchInput.addEventListener('input', handleSearch);
    searchClear.addEventListener('click', clearSearch);
    
    // 筛选功能
    statusFilter.addEventListener('change', handleFilter);
    typeFilter.addEventListener('change', handleFilter);
    dateFilter.addEventListener('change', handleFilter);
    resetFiltersBtn.addEventListener('click', resetFilters);
    
    // 视图切换
    viewBtns.forEach(btn => {
        btn.addEventListener('click', () => switchView(btn.dataset.view));
    });
    
    // 按钮事件
    createActivityBtn.addEventListener('click', openCreateModal);
    activityTemplateBtn.addEventListener('click', openTemplateModal);
    exportBtn.addEventListener('click', exportActivities);
    
    // 模态框事件
    document.addEventListener('click', handleModalClick);
    document.addEventListener('keydown', handleKeyDown);
    
    // 表格排序
    document.querySelectorAll('.sortable').forEach(th => {
        th.addEventListener('click', () => handleSort(th.dataset.sort));
    });
}

// 搜索处理
function handleSearch() {
    const query = searchInput.value.toLowerCase().trim();
    
    if (query) {
        searchClear.style.display = 'block';
        filteredActivities = activities.filter(activity => 
            activity.name.toLowerCase().includes(query) ||
            activity.theme.toLowerCase().includes(query) ||
            activity.number.toLowerCase().includes(query)
        );
    } else {
        searchClear.style.display = 'none';
        filteredActivities = [...activities];
    }
    
    applyFilters();
    renderActivities();
}

// 清除搜索
function clearSearch() {
    searchInput.value = '';
    searchClear.style.display = 'none';
    filteredActivities = [...activities];
    applyFilters();
    renderActivities();
}

// 筛选处理
function handleFilter() {
    applyFilters();
    renderActivities();
}

// 应用筛选条件
function applyFilters() {
    let filtered = filteredActivities;
    
    // 状态筛选
    const status = statusFilter.value;
    if (status) {
        filtered = filtered.filter(activity => activity.status === status);
    }
    
    // 类型筛选
    const type = typeFilter.value;
    if (type) {
        filtered = filtered.filter(activity => activity.type === type);
    }
    
    // 时间筛选
    const dateRange = dateFilter.value;
    if (dateRange) {
        filtered = filtered.filter(activity => {
            const activityDate = new Date(activity.date);
            const today = new Date();
            
            switch (dateRange) {
                case '今天':
                    return activityDate.toDateString() === today.toDateString();
                case '本周':
                    const weekStart = new Date(today.setDate(today.getDate() - today.getDay()));
                    const weekEnd = new Date(today.setDate(today.getDate() - today.getDay() + 6));
                    return activityDate >= weekStart && activityDate <= weekEnd;
                case '本月':
                    return activityDate.getMonth() === today.getMonth() && 
                           activityDate.getFullYear() === today.getFullYear();
                case '下月':
                    const nextMonth = new Date(today.getFullYear(), today.getMonth() + 1, 1);
                    return activityDate.getMonth() === nextMonth.getMonth() && 
                           activityDate.getFullYear() === nextMonth.getFullYear();
                default:
                    return true;
            }
        });
    }
    
    filteredActivities = filtered;
    updateResultCount();
}

// 重置筛选
function resetFilters() {
    searchInput.value = '';
    statusFilter.value = '';
    typeFilter.value = '';
    dateFilter.value = '';
    searchClear.style.display = 'none';
    
    filteredActivities = [...activities];
    renderActivities();
    updateResultCount();
}

// 视图切换
function switchView(view) {
    currentView = view;
    
    // 更新按钮状态
    viewBtns.forEach(btn => {
        btn.classList.toggle('active', btn.dataset.view === view);
    });
    
    // 切换视图
    if (view === 'table') {
        tableView.style.display = 'block';
        gridView.style.display = 'none';
    } else {
        tableView.style.display = 'none';
        gridView.style.display = 'block';
    }
}

// 加载活动数据
function loadActivities() {
    // 模拟数据，实际应从API获取
    activities = [
        {
            id: 1,
            number: 'ACT20250721001',
            name: '桂林山水3日游分享会',
            theme: '体验桂林山水之美，享受悠闲假期',
            type: '产品推介会',
            date: '2025-07-25',
            startTime: '14:30',
            endTime: '16:30',
            venue: '市民文化中心',
            address: '多功能厅A',
            invitedCount: 156,
            confirmedCount: 98,
            participationRate: 62.8,
            status: '筹备中'
        },
        {
            id: 2,
            number: 'ACT20250720001',
            name: '厦门鼓浪屿文艺之旅',
            theme: '感受海滨城市的浪漫与文艺气息',
            type: '目的地分享会',
            date: '2025-07-23',
            startTime: '09:30',
            endTime: '11:30',
            venue: '社区活动中心',
            address: '会议室B',
            invitedCount: 85,
            confirmedCount: 67,
            participationRate: 78.8,
            status: '进行中'
        },
        {
            id: 3,
            number: 'ACT20250718001',
            name: '夏季老客户答谢茶话会',
            theme: '感谢老客户的支持与信任',
            type: '客户答谢会',
            date: '2025-07-20',
            startTime: '15:00',
            endTime: '17:00',
            venue: '公司会议室',
            address: '3楼大会议室',
            invitedCount: 45,
            confirmedCount: 38,
            participationRate: 84.4,
            status: '已结束'
        }
    ];
    
    filteredActivities = [...activities];
    renderActivities();
    updateResultCount();
}

// 渲染活动列表
function renderActivities() {
    if (currentView === 'table') {
        renderTableView();
    } else {
        renderGridView();
    }
}

// 渲染表格视图
function renderTableView() {
    const tbody = document.getElementById('activity-table-body');
    tbody.innerHTML = '';
    
    filteredActivities.forEach(activity => {
        const row = createTableRow(activity);
        tbody.appendChild(row);
    });
}

// 创建表格行
function createTableRow(activity) {
    const row = document.createElement('tr');
    row.className = 'activity-row';
    row.dataset.activityId = activity.id;
    
    row.innerHTML = `
        <td class="activity-number">${activity.number}</td>
        <td class="activity-name">
            <div class="activity-info">
                <div class="activity-title">${activity.name}</div>
                <div class="activity-theme">${activity.theme}</div>
            </div>
        </td>
        <td>
            <span class="type-badge ${getTypeBadgeClass(activity.type)}">${activity.type}</span>
        </td>
        <td>
            <div class="date-info">
                <div class="date">${activity.date}</div>
                <div class="time">${activity.startTime}-${activity.endTime}</div>
            </div>
        </td>
        <td>
            <div class="location-info">
                <div class="venue">${activity.venue}</div>
                <div class="address">${activity.address}</div>
            </div>
        </td>
        <td class="invited-count">${activity.invitedCount}</td>
        <td class="confirmed-count">${activity.confirmedCount}</td>
        <td class="participation-rate">
            <div class="rate-bar">
                <div class="rate-fill" style="width: ${activity.participationRate}%"></div>
            </div>
            <span class="rate-text">${activity.participationRate}%</span>
        </td>
        <td>
            <span class="status-badge ${getStatusBadgeClass(activity.status)}">${activity.status}</span>
        </td>
        <td class="actions">
            <div class="action-buttons">
                ${getActionButtons(activity)}
            </div>
        </td>
    `;
    
    return row;
}

// 渲染网格视图
function renderGridView() {
    const container = document.getElementById('activity-grid-body');
    container.innerHTML = '';
    
    filteredActivities.forEach(activity => {
        const card = createActivityCard(activity);
        container.appendChild(card);
    });
}

// 创建活动卡片
function createActivityCard(activity) {
    const card = document.createElement('div');
    card.className = 'activity-card';
    card.dataset.activityId = activity.id;
    card.onclick = () => viewActivity(activity.id);
    
    card.innerHTML = `
        <div class="card-header">
            <div class="activity-type">
                <span class="type-badge ${getTypeBadgeClass(activity.type)}">${activity.type}</span>
            </div>
            <div class="activity-status">
                <span class="status-badge ${getStatusBadgeClass(activity.status)}">${activity.status}</span>
            </div>
        </div>
        
        <div class="card-body">
            <div class="activity-title">${activity.name}</div>
            <div class="activity-theme">${activity.theme}</div>
            
            <div class="activity-details">
                <div class="detail-item">
                    <i class="fas fa-calendar-alt"></i>
                    <span>${activity.date}</span>
                </div>
                <div class="detail-item">
                    <i class="fas fa-clock"></i>
                    <span>${activity.startTime}-${activity.endTime}</span>
                </div>
                <div class="detail-item">
                    <i class="fas fa-map-marker-alt"></i>
                    <span>${activity.venue}</span>
                </div>
            </div>

            <div class="participation-stats">
                <div class="stat-item">
                    <div class="stat-number">${activity.invitedCount}</div>
                    <div class="stat-label">已邀请</div>
                </div>
                <div class="stat-item">
                    <div class="stat-number">${activity.confirmedCount}</div>
                    <div class="stat-label">已确认</div>
                </div>
                <div class="stat-item">
                    <div class="stat-number">${activity.participationRate}%</div>
                    <div class="stat-label">参与率</div>
                </div>
            </div>

            <div class="progress-bar">
                <div class="progress-fill" style="width: ${activity.participationRate}%"></div>
            </div>
        </div>

        <div class="card-footer">
            ${getCardFooterButtons(activity)}
        </div>
    `;
    
    return card;
}

// 获取类型徽章样式类
function getTypeBadgeClass(type) {
    const typeMap = {
        '产品推介会': 'type-presentation',
        '目的地分享会': 'type-destination',
        '客户答谢会': 'type-appreciation',
        '小型茶话会': 'type-tea',
        '线上活动': 'type-online'
    };
    return typeMap[type] || 'type-presentation';
}

// 获取状态徽章样式类
function getStatusBadgeClass(status) {
    const statusMap = {
        '筹备中': 'status-preparing',
        '进行中': 'status-ongoing',
        '已结束': 'status-finished',
        '已取消': 'status-cancelled'
    };
    return statusMap[status] || 'status-preparing';
}

// 获取操作按钮
function getActionButtons(activity) {
    let buttons = `
        <button class="action-btn" title="查看详情" onclick="viewActivity(${activity.id})">
            <i class="fas fa-eye"></i>
        </button>
    `;
    
    if (activity.status === '筹备中') {
        buttons += `
            <button class="action-btn" title="编辑" onclick="editActivity(${activity.id})">
                <i class="fas fa-edit"></i>
            </button>
            <button class="action-btn" title="客户管理" onclick="manageInvitations(${activity.id})">
                <i class="fas fa-users"></i>
            </button>
        `;
    } else if (activity.status === '进行中') {
        buttons += `
            <button class="action-btn" title="现场管理" onclick="manageOnsite(${activity.id})">
                <i class="fas fa-clipboard-check"></i>
            </button>
            <button class="action-btn" title="客户管理" onclick="manageInvitations(${activity.id})">
                <i class="fas fa-users"></i>
            </button>
        `;
    } else if (activity.status === '已结束') {
        buttons += `
            <button class="action-btn" title="效果分析" onclick="analyzeResults(${activity.id})">
                <i class="fas fa-chart-line"></i>
            </button>
            <button class="action-btn" title="后续跟进" onclick="manageFollowup(${activity.id})">
                <i class="fas fa-tasks"></i>
            </button>
        `;
    }
    
    buttons += `
        <button class="action-btn" title="更多操作" onclick="showMoreActions(${activity.id})">
            <i class="fas fa-ellipsis-h"></i>
        </button>
    `;
    
    return buttons;
}

// 获取卡片底部按钮
function getCardFooterButtons(activity) {
    if (activity.status === '筹备中') {
        return `
            <button class="card-footer-btn primary" onclick="editActivity(${activity.id}, event)">
                <i class="fas fa-edit"></i>
                <span>编辑活动</span>
            </button>
            <button class="card-footer-btn secondary" onclick="manageInvitations(${activity.id}, event)">
                <i class="fas fa-users"></i>
                <span>客户管理</span>
            </button>
        `;
    } else if (activity.status === '进行中') {
        return `
            <button class="card-footer-btn primary" onclick="manageOnsite(${activity.id}, event)">
                <i class="fas fa-clipboard-check"></i>
                <span>现场管理</span>
            </button>
            <button class="card-footer-btn secondary" onclick="manageInvitations(${activity.id}, event)">
                <i class="fas fa-users"></i>
                <span>客户管理</span>
            </button>
        `;
    } else if (activity.status === '已结束') {
        return `
            <button class="card-footer-btn primary" onclick="analyzeResults(${activity.id}, event)">
                <i class="fas fa-chart-line"></i>
                <span>效果分析</span>
            </button>
            <button class="card-footer-btn secondary" onclick="manageFollowup(${activity.id}, event)">
                <i class="fas fa-tasks"></i>
                <span>后续跟进</span>
            </button>
        `;
    }
    return '';
}

// 更新结果计数
function updateResultCount() {
    const countElement = document.querySelector('.result-count');
    countElement.textContent = `共 ${filteredActivities.length} 个活动`;
}

// 更新统计数据
function updateStats() {
    // 模拟统计数据计算
    const stats = {
        ongoing: activities.filter(a => a.status === '进行中').length,
        totalInvited: activities.reduce((sum, a) => sum + a.invitedCount, 0),
        totalConfirmed: activities.reduce((sum, a) => sum + a.confirmedCount, 0),
        avgParticipation: activities.reduce((sum, a) => sum + a.participationRate, 0) / activities.length
    };
    
    // 更新统计卡片
    document.querySelector('.stats-grid .stat-card:nth-child(1) .stat-number').textContent = stats.ongoing;
    document.querySelector('.stats-grid .stat-card:nth-child(2) .stat-number').textContent = stats.totalInvited.toLocaleString();
    document.querySelector('.stats-grid .stat-card:nth-child(3) .stat-number').textContent = stats.totalConfirmed.toLocaleString();
    document.querySelector('.stats-grid .stat-card:nth-child(4) .stat-number').textContent = `${stats.avgParticipation.toFixed(1)}%`;
}

// 排序处理
function handleSort(field) {
    // 实现排序逻辑
    filteredActivities.sort((a, b) => {
        if (field === 'date') {
            return new Date(a.date) - new Date(b.date);
        } else if (field === 'name') {
            return a.name.localeCompare(b.name);
        } else if (field === 'activity_number') {
            return a.number.localeCompare(b.number);
        }
        return 0;
    });
    
    renderActivities();
}

// 活动操作函数
function viewActivity(id, event) {
    if (event) event.stopPropagation();
    showNotification('查看活动详情功能正在开发中...', 'info');
}

function editActivity(id, event) {
    if (event) event.stopPropagation();
    showNotification('编辑活动功能正在开发中...', 'info');
}

function manageInvitations(id, event) {
    if (event) event.stopPropagation();
    
    // 跳转到客户邀请管理页面
    window.location.href = `invitation-customer-management.html?activityId=${id}`;
}

function manageOnsite(id, event) {
    if (event) event.stopPropagation();
    showNotification('现场管理功能正在开发中...', 'info');
}

function analyzeResults(id, event) {
    if (event) event.stopPropagation();
    
    // 跳转到效果评估页面
    window.location.href = `activity-effect-evaluation.html?activityId=${id}`;
}

function manageFollowup(id, event) {
    if (event) event.stopPropagation();
    
    // 跳转到效果评估页面的后续跟进模块
    window.location.href = `activity-effect-evaluation.html?activityId=${id}&section=follow-up`;
}

function showMoreActions(id, event) {
    if (event) event.stopPropagation();
    currentActivityId = id;
    actionMenuModal.classList.add('show');
}

// 模态框相关函数
function openCreateModal() {
    createModal.classList.add('show');
}

function closeCreateModal() {
    createModal.classList.remove('show');
    document.getElementById('activity-form').reset();
}

function openTemplateModal() {
    showNotification('活动模板功能正在开发中...', 'info');
}

function saveActivity() {
    // 获取表单数据
    const form = document.getElementById('activity-form');
    const formData = new FormData(form);
    
    // 获取基本字段
    const activityData = {
        name: formData.get('activity-name'),
        type: formData.get('activity-type'),
        theme: formData.get('activity-theme'),
        date: formData.get('activity-date'),
        startTime: formData.get('start-time'),
        endTime: formData.get('end-time'),
        venue: formData.get('venue'),
        capacity: formData.get('capacity'),
        address: formData.get('address'),
        description: formData.get('activity-description'),
        expectedAttendance: formData.get('expected-attendance'),
        budget: formData.get('budget'),
        contactPerson: formData.get('contact-person'),
        invitationDeadline: formData.get('invitation-deadline'),
        reminderDays: formData.get('reminder-days'),
        invitationMessage: formData.get('invitation-message'),
        specialRequirements: formData.get('special-requirements'),
        status: formData.get('activity-status')
    };
    
    // 获取多选字段
    const targetAudience = Array.from(form.querySelectorAll('#target-audience option:checked')).map(opt => opt.value);
    const invitationMethods = Array.from(form.querySelectorAll('input[name="invitation-method"]:checked')).map(input => input.value);
    
    activityData.targetAudience = targetAudience;
    activityData.invitationMethods = invitationMethods;
    
    // 验证必填字段
    const requiredFields = [
        { field: 'name', name: '活动名称' },
        { field: 'type', name: '活动类型' },
        { field: 'date', name: '活动日期' },
        { field: 'startTime', name: '开始时间' },
        { field: 'endTime', name: '结束时间' },
        { field: 'venue', name: '活动地点' },
        { field: 'contactPerson', name: '活动负责人' }
    ];
    
    for (const { field, name } of requiredFields) {
        if (!activityData[field]) {
            showNotification(`请填写${name}`, 'error');
            return;
        }
    }
    
    // 验证时间逻辑
    if (activityData.startTime >= activityData.endTime) {
        showNotification('结束时间必须晚于开始时间', 'error');
        return;
    }
    
    // 验证日期不能是过去
    const selectedDate = new Date(activityData.date);
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    
    if (selectedDate < today) {
        showNotification('活动日期不能是过去的日期', 'error');
        return;
    }
    
    // 验证人数逻辑
    if (activityData.expectedAttendance && activityData.capacity) {
        if (parseInt(activityData.expectedAttendance) > parseInt(activityData.capacity)) {
            showNotification('预期参与人数不能超过场地容纳人数', 'error');
            return;
        }
    }
    
    // 验证邀请截止时间
    if (activityData.invitationDeadline) {
        const deadline = new Date(activityData.invitationDeadline);
        const activityDateTime = new Date(`${activityData.date}T${activityData.startTime}`);
        
        if (deadline >= activityDateTime) {
            showNotification('邀请截止时间必须早于活动开始时间', 'error');
            return;
        }
    }
    
    // 显示保存中状态
    const saveBtn = document.querySelector('.modal-footer .btn-primary');
    const originalText = saveBtn.textContent;
    saveBtn.textContent = '保存中...';
    saveBtn.disabled = true;
    
    // 模拟API调用
    setTimeout(() => {
        // 生成活动ID
        const activityId = 'ACT' + Date.now();
        activityData.id = activityId;
        activityData.number = activityId;
        activityData.createdTime = new Date().toISOString();
        activityData.invitedCount = 0;
        activityData.confirmedCount = 0;
        activityData.participationRate = 0;
        
        // 添加到活动列表
        activities.unshift(activityData);
        
        // 恢复按钮状态
        saveBtn.textContent = originalText;
        saveBtn.disabled = false;
        
        // 显示成功消息
        showNotification('活动创建成功！', 'success');
        closeCreateModal();
        
        // 重新渲染数据
        updateStats();
        renderActivities();
        
        // 可选：自动跳转到客户邀请界面
        if (confirm('活动创建成功！是否立即开始邀请客户？')) {
            manageInvitations(activityData.id);
        }
    }, 1500);
}

function closeActionMenu() {
    actionMenuModal.classList.remove('show');
    currentActivityId = null;
}

// 操作菜单函数
function duplicateActivity() {
    showNotification('复制活动功能正在开发中...', 'info');
    closeActionMenu();
}

function exportActivity() {
    showNotification('导出数据功能正在开发中...', 'info');
    closeActionMenu();
}

function sendReminder() {
    showNotification('发送提醒功能正在开发中...', 'info');
    closeActionMenu();
}

function viewHistory() {
    showNotification('查看历史功能正在开发中...', 'info');
    closeActionMenu();
}

function cancelActivity() {
    if (confirm('确定要取消这个活动吗？此操作不可撤销。')) {
        showNotification('活动已取消', 'success');
        closeActionMenu();
    }
}

function exportActivities() {
    showNotification('导出活动报表功能正在开发中...', 'info');
}

// 通用函数
function handleModalClick(event) {
    if (event.target.classList.contains('modal-overlay')) {
        closeCreateModal();
        closeActionMenu();
    }
}

function handleKeyDown(event) {
    if (event.key === 'Escape') {
        closeCreateModal();
        closeActionMenu();
    }
}

function showNotification(message, type = 'info') {
    // 创建通知元素
    const notification = document.createElement('div');
    notification.className = `alert alert-${type}`;
    notification.innerHTML = `
        <i class="fas fa-${getNotificationIcon(type)}"></i>
        <span>${message}</span>
    `;
    
    // 添加到页面
    document.body.appendChild(notification);
    
    // 定位
    notification.style.position = 'fixed';
    notification.style.top = '80px';
    notification.style.right = '20px';
    notification.style.zIndex = '9999';
    notification.style.minWidth = '300px';
    notification.style.animation = 'slideInRight 0.3s ease-out';
    
    // 自动移除
    setTimeout(() => {
        notification.style.animation = 'slideOutRight 0.3s ease-in';
        setTimeout(() => {
            document.body.removeChild(notification);
        }, 300);
    }, 3000);
}

function getNotificationIcon(type) {
    const iconMap = {
        'info': 'info-circle',
        'success': 'check-circle',
        'warning': 'exclamation-triangle',
        'error': 'times-circle'
    };
    return iconMap[type] || 'info-circle';
}

// 添加动画样式
const style = document.createElement('style');
style.textContent = `
    @keyframes slideInRight {
        from {
            transform: translateX(100%);
            opacity: 0;
        }
        to {
            transform: translateX(0);
            opacity: 1;
        }
    }
    
    @keyframes slideOutRight {
        from {
            transform: translateX(0);
            opacity: 1;
        }
        to {
            transform: translateX(100%);
            opacity: 0;
        }
    }
`;
document.head.appendChild(style);